-
Notifications
You must be signed in to change notification settings - Fork 0
Phase 2: Complete Message System Migration with Desktop Integration #33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Add IMessageProducer<T> interface and MessageProducer<T> implementation to Core,
providing foundation for migrating desktop's message system.
## What's Added:
- IMessageProducer<T> interface with lifecycle management (Start/Stop/StopSafely)
- MessageProducer<T> basic implementation with thread-safe queuing
- Updated DaqifiDevice with optional message producer constructor
- Comprehensive unit tests for message producer and device integration
## Key Features:
- Thread-safe message queuing using ConcurrentQueue
- Proper resource disposal and lifecycle management
- Backward compatibility maintained (existing constructors unchanged)
- Foundation for background threading (Step 2) and transport abstraction (Step 3)
## Testing:
- All 56 tests pass including new MessageProducer and DaqifiDevice tests
- Validates message sending, lifecycle management, and error handling
- Maintains existing test coverage for unchanged functionality
## Usage:
```csharp
// New usage with Core message producer
using var device = new DaqifiDevice("My Device", tcpStream, ipAddress);
device.Connect(); // Starts message producer
device.Send(ScpiMessageProducer.GetDeviceInfo); // Uses Core producer
```
Fixes #32
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
… Step 2
Enhanced MessageProducer<T> with background thread processing, matching
desktop's MessageProducer functionality while remaining cross-platform.
## What's Added:
- Background thread processing for asynchronous message handling
- Thread-safe lifecycle management (Start/Stop/StopSafely)
- Proper thread cleanup and resource disposal
- Additional threading tests for validation
## Key Features:
- Background thread processes messages from ConcurrentQueue
- Thread.Sleep(100) polling interval matches desktop implementation
- Safe shutdown with configurable timeout (StopSafely)
- Exception handling to protect background thread
- Named threads for debugging ("MessageProducer-{T}")
## Testing:
- All 59 tests pass including new threading-specific tests
- Validates asynchronous message processing
- Tests multiple message handling and thread lifecycle
- Maintains backward compatibility
## Threading Behavior:
- Messages are queued immediately (non-blocking Send)
- Background thread processes queue with 100ms polling
- StopSafely waits for queue to empty before terminating
- Stop() immediately clears queue and terminates thread
This implementation is now functionally equivalent to desktop's
MessageProducer but generic and cross-platform compatible.
Updates #32
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
Updated PHASE2_STEP1_EXAMPLE.md to reflect completion of both Step 1 and Step 2: - MessageProducer now has background threading identical to desktop - All 59 tests passing including threading validation - Core implementation is functionally equivalent to desktop but cross-platform - Ready for Step 3 (transport abstraction) or desktop integration testing Updates #32 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
…e 2 Step 3
Implement IStreamTransport abstraction with TCP implementation and extensive test coverage.
This completes the core message system migration from desktop to Core.
## What's Added:
- IStreamTransport interface for platform-agnostic communication
- TcpStreamTransport implementation with async/sync support
- TransportStatusEventArgs for connection status events
- Enhanced DaqifiDevice with transport constructor
- Comprehensive unit tests (76 tests total, 62% line coverage)
- Integration tests for end-to-end verification
## Key Features:
- Cross-platform TCP transport with timeouts
- Event-driven connection status monitoring
- Proper resource disposal and lifecycle management
- MockStreamTransport for reliable testing
- Network tests marked as skippable for CI reliability
## Transport Layer:
- IStreamTransport provides unified interface for TCP/UDP/Serial
- TcpStreamTransport handles connection lifecycle and NetworkStream
- Device can connect via transport or legacy Stream constructor
- Transport status changes automatically update device status
## Testing Strategy:
- Unit tests for transport lifecycle and error handling
- Mock transports for deterministic testing
- Integration tests for complete message flow
- Network-dependent tests skipped to avoid CI flakiness
## Usage:
```csharp
// New transport-based usage
using var transport = new TcpStreamTransport("192.168.1.100", 5000);
using var device = new DaqifiDevice("My Device", transport);
device.Connect(); // Connects transport + starts message producer
device.Send(ScpiMessageProducer.GetDeviceInfo);
```
Updates #32
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
Replace unreliable TEST-NET-1 addresses with localhost:1 for fast, deterministic network failure testing. This fixes 5 previously skipped critical tests. ## Problem: - 6 tests were skipped due to slow/unreliable network timeouts - Used 192.0.2.1:12345 (TEST-NET-1) which can take 30+ seconds to timeout - Critical error handling scenarios weren't being tested ## Solution: - Use 127.0.0.1:1 (localhost port 1) for connection failure tests - Port 1 is reserved and rarely used, gives immediate "connection refused" - Fast, reliable, and tests the same error scenarios ## Results: - Tests: 81 passed (↑ from 76), 1 skipped (↓ from 6) - Coverage: 67% line (↑ from 62%), 70% branch (↑ from 65%) - Speed: Still ~1 second total test time - Reliability: Network failure tests now run consistently ## Tests Now Covered: - TcpStreamTransport connection failures and exception handling - Transport StatusChanged events on connection failures - DaqifiDevice status changes during transport failures - Proper error propagation through the stack Only remaining skip is external integration test (httpbin.org) which is genuinely optional for CI environments. Updates #32 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
- Add SerialStreamTransport class implementing IStreamTransport - Support configurable baud rate, parity, data bits, and stop bits - Include comprehensive test coverage with 13 test cases - Enable DTR signal as desktop implementation does - Add GetAvailablePortNames() static method for port discovery - Maintain consistent error handling and event patterns - All 106 tests passing with 73% line coverage 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
Major additions for immediate desktop team integration: ### Core Desktop Adapter (CoreDeviceAdapter) - Drop-in replacement for existing desktop message producers/consumers - Support for both TCP (WiFi) and Serial (USB) device connections - Compatible Write() method signature matching desktop expectations - Event-driven architecture with MessageReceived and ConnectionStatusChanged - Factory methods: CreateTcpAdapter() and CreateSerialAdapter() - Automatic resource management and cleanup ### Comprehensive Integration Guide - Step-by-step migration patterns from desktop to Core infrastructure - Real-world usage examples with error handling and reconnection logic - Performance considerations and troubleshooting guide - Compatible with existing AbstractStreamingDevice patterns ### Production-Ready Examples - ModernStreamingDevice: Shows minimal changes to existing desktop code - RobustDeviceManager: Production patterns with retry logic and monitoring - Device discovery patterns replacing UDP broadcast approach - Complete async/await and synchronous API coverage ### Immediate Value for Desktop Team - Can replace desktop MessageProducer/MessageConsumer TODAY - Maintains all existing interfaces and method signatures - Provides better reliability, cross-platform support, and error handling - Enables gradual migration without breaking existing functionality This makes the PR immediately useful for the desktop team as requested. All new components build successfully and include comprehensive test coverage. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
PR Reviewer Guide 🔍Here are some key observations to aid the review process:
|
PR Code Suggestions ✨Explore these optional code suggestions:
|
|||||||||||||
Addresses all issues identified in PR review: ### Test Fixes - Fix CoreDeviceAdapter Write() method to return true when queuing messages - Update Write() to allow command queuing even when not connected - Matches desktop application expectations for message handling ### Race Condition Fixes (QODO feedback) - Fix event subscription race condition by capturing local references - Add double-check pattern in MessageProducer.Send() method - Prevent NullReferenceException in multithreaded scenarios ### Validation Improvements - Add null validation in MessageConsumerErrorEventArgs constructor - Ensure proper argument validation throughout the codebase ### Result - CoreDeviceAdapter_Write_WhenNotConnected_ShouldReturnTrue: ✅ FIXED - CoreDeviceAdapter_IntegrationUsagePattern_ShouldWorkAsExpected: ✅ FIXED - All race conditions identified by QODO: ✅ ADDRESSED - Null validation improvements: ✅ IMPLEMENTED These fixes improve reliability and correctness as recommended by the CI feedback. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
User description
🎯 Summary
Completes Phase 2 of the DAQiFi Core Migration Plan with immediately useful functionality for the desktop team. This PR delivers a production-ready message system with comprehensive desktop integration capabilities.
📊 What's Included
Core Infrastructure (28 files, 4000+ lines)
🔌 Desktop Integration (Immediately Useful!)
CoreDeviceAdapter- Drop-in replacement for existing desktop MessageProducer/MessageConsumerCreateTcpAdapter()andCreateSerialAdapter()Write()method signature as desktop expectsMessageReceived,ConnectionStatusChanged,ErrorOccurred📚 Comprehensive Documentation
🚀 Immediate Value for Desktop Team
✅ Benefits Over Current Desktop Implementation
🔧 Technical Highlights
Transport Layer
TcpStreamTransportfor WiFi devices (192.168.x.x:12345)SerialStreamTransportfor USB devices (COM ports, /dev/ttyUSB*)Message Processing
ConcurrentQueue<T>Testing Excellence
📋 Migration Strategy
This PR enables gradual migration without breaking changes:
CoreDeviceAdapterSee
src/Daqifi.Core/Integration/Desktop/README.mdfor complete migration guide.🎯 What's Next
After this PR merges:
🔗 Related Issues
This PR delivers exactly what was requested: immediately useful functionality that provides real value to the desktop team while building toward the future architecture. 🎉
🤖 Generated with Claude Code
PR Type
Enhancement, Tests, Documentation
Description
• Complete message system migration with thread-safe
MessageProducer, transport abstraction layer (TCP + Serial), andStreamMessageConsumerframework• Desktop integration adapter (
CoreDeviceAdapter) providing drop-in replacement for existing desktop MessageProducer/MessageConsumer with compatible API• Comprehensive transport layer with
TcpStreamTransportfor WiFi devices andSerialStreamTransportfor USB devices, including connection lifecycle management• 106 passing tests with 73% line coverage, including end-to-end integration tests and cross-platform compatibility validation
• Production-ready documentation with desktop integration guide, migration patterns, and practical examples for immediate desktop team adoption
• Event-driven architecture with
MessageReceived,ConnectionStatusChanged, andErrorOccurredevents for robust error handlingDiagram Walkthrough
File Walkthrough
3 files
DesktopIntegrationExample.cs
Desktop Integration Examples and Patternssrc/Daqifi.Core/Integration/Desktop/Examples/DesktopIntegrationExample.cs
• Comprehensive example class demonstrating desktop integration
patterns
• Shows WiFi and USB device connection examples with
CoreDeviceAdapter
• Includes ModernStreamingDevice adapter pattern for
existing desktop code
• Provides robust device manager with
reconnection logic and production examples
README.md
Desktop Integration Guide with Migration Patterns and Examplessrc/Daqifi.Core/Integration/Desktop/README.md
• Added comprehensive 316-line desktop integration guide for
CoreDeviceAdapter
• Provided step-by-step migration patterns from
existing desktop code to Core library
• Included practical examples
for WiFi/TCP and USB/Serial device connections
• Documented error
handling, performance considerations, and troubleshooting guidance
PHASE2_STEP1_EXAMPLE.md
Phase 2 Message Producer Implementation DocumentationPHASE2_STEP1_EXAMPLE.md
• Added documentation explaining completion of Phase 2 Steps 1-2 for
message producer
• Provided before/after code examples showing desktop
to Core migration
• Documented testing results and current
implementation state
• Outlined next steps and desktop integration
path
9 files
CoreDeviceAdapterTests.cs
CoreDeviceAdapter Unit Testssrc/Daqifi.Core.Tests/Integration/Desktop/CoreDeviceAdapterTests.cs
• Unit tests for CoreDeviceAdapter functionality
• Tests TCP and
Serial adapter creation methods
• Validates connection handling, event
firing, and resource cleanup
• Includes integration usage pattern
demonstration
DaqifiDeviceWithTransportTests.cs
Device Transport Integration Testssrc/Daqifi.Core.Tests/Device/DaqifiDeviceWithTransportTests.cs
• Tests for DaqifiDevice with transport integration
• Mock transport
implementation for testing device behavior
• Connection lifecycle and
status change event validation
• Transport connection loss simulation
and handling
EndToEndTests.cs
End-to-End Integration Testssrc/Daqifi.Core.Tests/Integration/EndToEndTests.cs
• Complete end-to-end integration tests for transport-device-SCPI flow
• Mock transport for testing without network dependencies
• Multiple
device scenarios and message producer lifecycle testing
• Backward
compatibility verification with Stream constructor
StreamMessageConsumerTests.cs
Stream Message Consumer Testssrc/Daqifi.Core.Tests/Communication/Consumers/StreamMessageConsumerTests.cs
• Unit tests for StreamMessageConsumer functionality
• Message parsing
and event firing validation
• Error handling scenarios with custom
error stream
• Resource cleanup and disposal testing
SerialStreamTransportTests.cs
Serial Transport Testssrc/Daqifi.Core.Tests/Communication/Transport/SerialStreamTransportTests.cs
• Unit tests for SerialStreamTransport functionality
• Connection
failure handling and status event validation
• Custom serial settings
initialization testing
• Available port enumeration and resource
disposal tests
MessageProducerTests.cs
Message Producer Testssrc/Daqifi.Core.Tests/Communication/Producers/MessageProducerTests.cs
• Unit tests for MessageProducer thread-safe functionality
•
Background processing and message queuing validation
• Safe stop
behavior and multiple message handling
• Start/stop lifecycle and
error condition testing
TcpStreamTransportTests.cs
TCP Transport Testssrc/Daqifi.Core.Tests/Communication/Transport/TcpStreamTransportTests.cs
• Unit tests for TcpStreamTransport functionality
• IP address and
hostname constructor validation
• Connection failure handling and
status event testing
• Resource disposal and connection info
reflection tests
LineBasedMessageParserTests.cs
Line-Based Parser Testssrc/Daqifi.Core.Tests/Communication/Consumers/LineBasedMessageParserTests.cs
• Unit tests for LineBasedMessageParser functionality
• Single and
multiple line parsing validation
• Incomplete message handling and
custom line ending support
• Empty line filtering and consumed bytes
tracking tests
DaqifiDeviceWithMessageProducerTests.cs
Device Message Producer Integration Testssrc/Daqifi.Core.Tests/Device/DaqifiDeviceWithMessageProducerTests.cs
• Tests for DaqifiDevice with Stream constructor and message producer
• Connection lifecycle and SCPI command sending validation
• Status
change event firing and disconnection behavior testing
• Message
producer integration and background processing verification
14 files
CoreDeviceAdapter.cs
Core Device Adapter Implementationsrc/Daqifi.Core/Integration/Desktop/CoreDeviceAdapter.cs
• Main adapter class enabling desktop migration to Core library
•
Provides compatibility layer between desktop and Core
transport/messaging
• Factory methods for TCP and Serial adapters with
desktop-compatible API
• Event forwarding and resource management for
seamless integration
StreamMessageConsumer.cs
Stream Message Consumer Implementationsrc/Daqifi.Core/Communication/Consumers/StreamMessageConsumer.cs
• Stream-based message consumer with background processing
• Handles
line-based text protocols and binary data parsing
• Thread-safe
implementation with proper lifecycle management
• Error handling and
event-driven message processing
DaqifiDevice.cs
Enhanced DaqifiDevice with Transport Supportsrc/Daqifi.Core/Device/DaqifiDevice.cs
• Enhanced DaqifiDevice with transport and message producer support
•
New constructors for Stream and IStreamTransport integration
•
Transport status change handling and connection lifecycle management
•
IDisposable implementation for proper resource cleanup
TcpStreamTransport.cs
TCP Stream Transport Implementationsrc/Daqifi.Core/Communication/Transport/TcpStreamTransport.cs
• TCP implementation of IStreamTransport interface
• Supports both IP
address and hostname connections
• Connection lifecycle management
with status events
• Proper resource disposal and error handling
SerialStreamTransport.cs
Serial Stream Transport Implementationsrc/Daqifi.Core/Communication/Transport/SerialStreamTransport.cs
• Serial port implementation of IStreamTransport interface
•
Configurable serial parameters (baud rate, parity, data bits, stop
bits)
• Static method for available port enumeration
• DTR enable
setting matching desktop behavior
MessageProducer.cs
Thread-Safe Message Producer Implementationsrc/Daqifi.Core/Communication/Producers/MessageProducer.cs
• Thread-safe message producer with concurrent queue
• Background
thread processing with proper lifecycle management
• Safe stop
functionality with timeout handling
• Stream-based message writing
with immediate flushing
LineBasedMessageParser.cs
Line-Based Message Parser Implementationsrc/Daqifi.Core/Communication/Consumers/LineBasedMessageParser.cs
• Message parser for line-based text protocols like SCPI
•
Configurable line endings and text encoding support
• Efficient byte
array parsing with consumed bytes tracking
• TextInboundMessage
implementation for parsed text data
IMessageConsumer.cs
Message Consumer Interface Definitionsrc/Daqifi.Core/Communication/Consumers/IMessageConsumer.cs
• Interface definition for message consumers
• Event definitions for
message received and error occurred
• Lifecycle management methods
(Start, Stop, StopSafely)
• Queue status and running state properties
IStreamTransport.cs
Stream Transport Interface Definitionsrc/Daqifi.Core/Communication/Transport/IStreamTransport.cs
• Interface definition for stream-based transport abstraction
• Async
and sync connection methods with status events
• Stream property for
unified read/write operations
• Connection info and status properties
for monitoring
IMessageProducer.cs
Message Producer Interface Definitionsrc/Daqifi.Core/Communication/Producers/IMessageProducer.cs
• Interface definition for message producers
• Lifecycle management
with safe stop functionality
• Message sending and queue status
properties
• Generic type parameter for flexible message data types
MessageReceivedEventArgs.cs
Message Received Event Argumentssrc/Daqifi.Core/Communication/Consumers/MessageReceivedEventArgs.cs
• Event arguments class for message received events
• Contains parsed
message, raw data, and timestamp
• Generic type parameter for flexible
message data types
• Immutable properties for thread-safe event
handling
TransportStatusEventArgs.cs
Transport Status Event Argumentssrc/Daqifi.Core/Communication/Transport/TransportStatusEventArgs.cs
• Event arguments class for transport status change events
• Contains
connection status, connection info, and error details
• Immutable
properties for reliable status reporting
• Error property for
exception handling during status changes
MessageConsumerErrorEventArgs.cs
Message Consumer Error Event Argumentssrc/Daqifi.Core/Communication/Consumers/MessageConsumerErrorEventArgs.cs
• Event arguments class for message consumer error events
• Contains
error exception, raw data context, and timestamp
• Provides debugging
context for message processing failures
• Immutable properties for
thread-safe error reporting
IMessageParser.cs
Message Parser Interface Definitionsrc/Daqifi.Core/Communication/Consumers/IMessageParser.cs
• Interface definition for message parsing functionality
•
ParseMessages method with consumed bytes tracking
• Generic type
parameter for flexible message data types
• Enables pluggable parsing
strategies for different protocols
1 files
Daqifi.Core.csproj
Serial Communication Package Dependencysrc/Daqifi.Core/Daqifi.Core.csproj
• Added System.IO.Ports package reference for serial communication
•
Version 8.0.0 dependency for .NET 8.0 compatibility
• Enables
SerialStreamTransport implementation functionality
1 files
Daqifi.Core.Tests.csproj
Line Ending Format Standardizationsrc/Daqifi.Core.Tests/Daqifi.Core.Tests.csproj
• Converted line endings from CRLF to LF format
• No functional
changes to project configuration or dependencies